package com.cnpc.rightslogan.controller;

import com.alibaba.fastjson.JSON;
import com.cnpc.rightslogan.pojo.Dictionary;
import com.cnpc.rightslogan.service.IDictionaryService;
import com.cnpc.rightslogan.utils.common.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/9/13.
 * 测试服务之间调用添加了/api  /api/** 不会参与登录验证
 */
@RestController
@RequestMapping("/api/dictionary")
@Api("DictionaryController相关的api")
@Slf4j
public class DictionaryController extends BaseController {

    @Autowired
    private IDictionaryService dictionaryServiceImpl;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation(value = "获取所有字典数据", notes = "获取所有字典数据")
    @ResponseBody
    @GetMapping("getDictionaryList")
    public List<Dictionary> getDictionaryList() {
        log.info("Dictionary模块-获取所有Dictionary数据");
        List<Dictionary> dictionaryList;
        String dictionaryJsonList;
        //如果Redis缓存有数据,从缓存中获取数据
        if (stringRedisTemplate.hasKey("dictionary")) {
            log.info("字典数据通过缓存获取.");
            dictionaryJsonList = stringRedisTemplate.opsForValue().get("dictionary");
            dictionaryList = JSON.parseArray(dictionaryJsonList, Dictionary.class);
            return dictionaryList;
        } else {    //如果Redis缓存没有数据,从数据库中获取数据   但是这种情况会导致缓存击穿   容易导致雪崩
            log.warn("字典数据通过数据库获取,此消息不应多次重复出现.");
            dictionaryList = dictionaryServiceImpl.getDictionaryList();
            dictionaryJsonList = JSON.toJSONString(dictionaryList);
            stringRedisTemplate.opsForValue().set("dictionary", dictionaryJsonList, 1 * 10, TimeUnit.SECONDS);
            return dictionaryList;
        }
    }
}